package com.wu.server.service;

import com.wu.server.Thread.MainThread;
import com.wu.server.code.Code;
import com.wu.server.dao.NewGoodsRepository;
import com.wu.server.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class GoodsServer {
    @Autowired
    NewGoodsRepository goodsRepository;
    @Autowired
    Code code;
    @Autowired
    MainThread mainThread;
    public Object queryGoods(String id,String goodsName, String shopName, String price, Boolean isSelf, String tagName, String sort, String order, int pageNum, int pageSize ){
        String goodsNameQuery = "%" + goodsName + "%";//  模糊查询
        String goodsIdQuery = !id.equals("") ? id : null;//  模糊查询
        String tagNameQuery = "%" + tagName + "%";//模糊查询
        String[] priceQuery = price.split(",");//价格区间
        String isSelfQuery = isSelf ? "%自营%": null;//模糊查询
        String shopNameQuery = "%" + shopName + "%";//模糊查询
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.fromString(order),sort);

        Page<Goods> goods = goodsRepository.findAllBy(goodsIdQuery,goodsNameQuery,priceQuery[0],priceQuery[1],isSelfQuery,tagNameQuery,shopNameQuery,pageable);
        List<Goods> data = goods.getContent();
        HashMap<String,Object> paging = new HashMap<>();
        paging.put("total",goods.getTotalElements());
        paging.put("pageNum",goods.getNumber()+1);
        paging.put("pageSize",goods.getSize());
        HashMap<String,Object> result = new HashMap<>();
        result.put("paging",paging);
        result.put("data",data);
        return code.getMeta(Code.SUCCESS,result);
    }
    public Object insertGoods(Goods goods){
        try {
            goodsRepository.save(goods);
            mainThread.run();
            return code.getMeta(Code.SUCCESS,goods);
        }catch (Exception e){
            return code.getMeta(Code.creatFail,null);
        }


    }
    public Object updateGoods(Goods goods) {
        try {
            goodsRepository.save(goods);
            mainThread.run();
            return code.getMeta(Code.SUCCESS,goods);
        }catch (Exception e){
            return code.getMeta(Code.updateFail,null);
        }
    }

    public Object deleteGoods(int id) {
        try {
            goodsRepository.deleteGoods(id);
            mainThread.run();
            return code.getMeta(Code.SUCCESS,null);
        }catch (Exception e){
            return code.getMeta(Code.deleteFail,null);
        }
    }
}
